package it.softphone.commons.json.server.converter;


import it.softphone.commons.json.server.JSONConverter;
import it.softphone.commons.json.server.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 
 * @author softphone
 *
 */
public class JSONCollectionConverter<T extends Collection<?>> implements JSONConverter<T> {

	
	@Override
	public Object convert(@SuppressWarnings("rawtypes") Class type, Object value) {

		if( JSONObject.NULL==value || value==null ) return null;
		
		Collection<?> source = null; 
		
		if( value instanceof it.softphone.commons.json.server.JSONArray ) {
			
			source = ((it.softphone.commons.json.server.JSONArray)value);
		}
		if( value instanceof it.softphone.commons.json.server.JSONObject ) {
			
			source = ((it.softphone.commons.json.server.JSONObject)value).values();
		}
		
		if( List.class.isAssignableFrom(type) ) {
			
			if( source != null ) {
				return new ArrayList<Object>( source );
			}
			return Collections.emptyList();
		}

		if( Set.class.isAssignableFrom(type) ) {
			
			if( source != null ) {
				return new HashSet<Object>( source );
			}
			return Collections.emptyList();
		}
		return 	null;	
	}

	@Override
	public Object convert( T value) {
		
		return (value == null ) ?  JSONObject.NULL : new it.softphone.commons.json.server.JSONArray(value);
	}

}
